import request from "@/utils/request.ts";
import type { getClassGroupListResponse, GetClassListParams, GetClassListResponse, adminUpdate, adminLogin, adminRegister, classManageInfo, pageInfo, adminForgetPassword, loginResponseDate, createClass, getGroupsDatePrams, allowAndSetProDatePrams, GetStudentsListParams, getClassStudentsListResponse } from "@/api/admin/type.ts";


enum API {
    CLASS_URL = "/api/class",
    ADMIN_URL = "/admin",
    FORGET_URL = "/admin/forget-password",
    UPDATE_URL = "/admin/update",
    CLASS_LIST_URL = "/class/page",
    CREATE_URL = "/class/create-class",
    DELETE_CLASS_URL = "/class/delete-class",
    CLASS_GROUP_LIST_URL = "/class/get-class-groups/page",
    ALLOW_AND_SET = "/group/project-evaluation-approval",
    EXPORT_GROUPS_URL = "/common/export-groups",
    CLASS_STUDENT_LIST_URL = "/class/get-studentsScore/page",
    EXPORT_STUDENT_URL = "/common/export-students"
}
//暴露管理端接口
//管理员(教师)登录
export const reqAdminLogin = (data: adminLogin) => request.post<adminLogin, any>(API.ADMIN_URL + "/login", data);
//管理员(教师)注册
export const reqAdminRegister = (data: adminRegister) => request.post<adminRegister, any>(API.ADMIN_URL + "/register", data);

//忘记密码接口的方法
export const reqAdminForgetPassword = (data: adminForgetPassword) => request.post<adminForgetPassword, loginResponseDate>(API.FORGET_URL, data);


// 更新接口的方法
export const reqAdminUpdateInfo = (data: adminUpdate) =>
    request.post<adminUpdate, loginResponseDate>(API.UPDATE_URL, data);


//获取自己班级信息的接口
export const reqGetClassList = (params: GetClassListParams) => {
    return request.get<GetClassListParams, GetClassListResponse>(API.CLASS_LIST_URL, { params });
};


// 创建新的班级的接口
export const reqCreateClass = (data: createClass) =>
    request.post<createClass, loginResponseDate>(API.CREATE_URL, data);


// 进行删除班级的接口  
export const reqDeleteClass = (classId: number): Promise<loginResponseDate> => {
    return request.delete<loginResponseDate>(`${API.DELETE_CLASS_URL}/${classId}`)
        .then(response => response.data) // 直接返回 data 部分
        .catch(error => {
            if (error.response) {
                // 请求已发出，但服务器响应的状态码不在 2xx 范围内
                console.error('Error:', error.response.data);
                throw new Error(error.response.data.msg || '请求失败');
            } else {
                // 其他错误（如网络错误）
                console.error('Error:', error.message);
                throw new Error('请求失败');
            }
        });
};

//获取自己班级中小组信息的接口
export const reqGetGroupList = (params: getGroupsDatePrams) => {
    return request.get<getGroupsDatePrams, getClassGroupListResponse>(API.CLASS_GROUP_LIST_URL, { params });
};

//进行打分立项提交的接口
export const reqAllowAndSetPro = (data: allowAndSetProDatePrams) => {
    return request.post<allowAndSetProDatePrams, loginResponseDate>(API.ALLOW_AND_SET, data);
};


//导出该班级小组信息的接口
export const reqExportGroupScore = async (classId: string) => {
    try {
        console.log("开始请求...");
        const response = await request({
            url: `${API.EXPORT_GROUPS_URL}/${classId}`, // 替换为实际接口URL
            method: 'get',
            responseType: 'blob', // 设置响应类型为 blob
        });
        if (response.status !== 200) {
            throw new Error(`服务器响应状态码：${response.status}`);
        }
        // 创建一个 Blob 对象
        const blob = new Blob([response.data], { type: response.headers['content-type'] });
        // 创建一个隐藏的 <a> 标签用于触发下载
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        // 从响应头中获取文件名
        const contentDisposition = response.headers['content-disposition'];
        let fileName = "download.xls";
        if (contentDisposition && contentDisposition.indexOf('attachment') !== -1) {
            const regex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            const matches = regex.exec(contentDisposition);
            if (matches != null && matches[1]) {
                fileName = decodeURIComponent(matches[1].replace(/['"]/g, ''));
            }
        }
        link.setAttribute('download', fileName); // 设置下载文件名

        document.body.appendChild(link); // 将 a 标签添加到页面中（某些浏览器需要）
        link.click(); // 触发点击事件开始下载
        link.remove(); // 下载完成后移除 a 标签
    } catch (error) {
        console.error("下载失败:", error);
        throw error; // 重新抛出错误以便上层处理
    }
};

//获取自己班级中学生信息的接口
export const reqGetStudentsScore = (params: GetStudentsListParams) => {
    return request.get<GetStudentsListParams, getClassStudentsListResponse>(API.CLASS_STUDENT_LIST_URL, { params });
};

//导出该班级学生信息的接口
export const reqExportStudentScore = async (classId: string) => {
    try {
        console.log("开始请求...");
        const response = await request({
            url: `${API.EXPORT_STUDENT_URL}/${classId}`, // 替换为实际接口URL
            method: 'get',
            responseType: 'blob', // 设置响应类型为 blob
        });
        if (response.status !== 200) {
            throw new Error(`服务器响应状态码：${response.status}`);
        }
        // 创建一个 Blob 对象
        const blob = new Blob([response.data], { type: response.headers['content-type'] });
        // 创建一个隐藏的 <a> 标签用于触发下载
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        // 从响应头中获取文件名
        const contentDisposition = response.headers['content-disposition'];
        let fileName = "download.xls";
        if (contentDisposition && contentDisposition.indexOf('attachment') !== -1) {
            const regex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            const matches = regex.exec(contentDisposition);
            if (matches != null && matches[1]) {
                fileName = decodeURIComponent(matches[1].replace(/['"]/g, ''));
            }
        }
        link.setAttribute('download', fileName); // 设置下载文件名

        document.body.appendChild(link); // 将 a 标签添加到页面中（某些浏览器需要）
        link.click(); // 触发点击事件开始下载
        link.remove(); // 下载完成后移除 a 标签
    } catch (error) {
        console.error("下载失败:", error);
        throw error; // 重新抛出错误以便上层处理
    }
};




//小组管理 获取小组列表
export const reqGetClasses = (adminId: number) => request.get<number, classManageInfo[]>(API.CLASS_URL + `/${adminId}/get-classes`);
